package com.suxin.utils;

import org.springframework.lang.Nullable;
import org.springframework.util.PropertyPlaceholderHelper;

import java.text.MessageFormat;
import java.util.Map;

/**
 * @author Tang
 * @classname ContextHolderUtils
 * @description [ 内容占位符替换 ]
 * @date 2021/12/23 11:07
 */
public class ContextHolderUtils {

    private static final String PLACE_HOLDER_PREFIX = "{$";

    private static final String PLACE_HOLDER_ENDFIX = "}";

    private static PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper(
            PLACE_HOLDER_PREFIX, PLACE_HOLDER_ENDFIX
    );

    public static String replacePlaceHolder(final String template, final Map<String, String> paramMap) {
        return propertyPlaceholderHelper.replacePlaceholders(template, new CustomizePlaceHolderResolver(paramMap));
    }

    public static class CustomizePlaceHolderResolver implements PropertyPlaceholderHelper.PlaceholderResolver {

        private Map<String, String> paramMap;

        public CustomizePlaceHolderResolver(Map<String, String> paramMap) {
            this.paramMap = paramMap;
        }

        @Nullable
        @Override
        public String resolvePlaceholder(String placeholderName) {
            String value = paramMap.get(placeholderName);
            if (value == null) {
                String errorStr = MessageFormat.format("template:{} require param:{},but no exist! paramMap:{}",
                        placeholderName, paramMap.toString());
                throw new IllegalArgumentException(errorStr);
            }
            return null;
        }
    }

}